package com.detech.sbom.base.satoken.handler;

import cn.dev33.satoken.exception.*;
import com.detech.sbom.base.domain.R;
import com.detech.sbom.base.domain.RE;
import com.detech.sbom.base.enumtype.CodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局权限处理器
 *
 */
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SatokenExceptionHandler {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 权限码异常
     */
    @ExceptionHandler(NotPermissionException.class)
    public RE handleNotPermissionException(NotPermissionException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.warn("请求地址'{}',权限码校验失败'{}'", requestURI, e.getMessage());
        return R.R(CodeEnum.noPermission, "权限码校验失败，无法访问系统资源");
    }

    /**
     * 角色权限异常
     */
    @ExceptionHandler(NotRoleException.class)
    public RE handleNotRoleException(NotRoleException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.warn("请求地址'{}',角色权限校验失败'{}'", requestURI, e.getMessage());
        return R.R(CodeEnum.noPermission, "角色权限校验失败，无法访问系统资源");
    }

    /**
     * 账号被封禁
     */
    @ExceptionHandler(DisableServiceException.class)
    public RE handleDisableLoginException(DisableServiceException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.warn("请求地址'{}',帐号已被封禁'{}',无法访问系统资源", requestURI, e.getMessage());
        return R.R(CodeEnum.authentication, "帐号已被封禁，无法访问系统资源");
    }

    /**
     * 认证失败
     */
    @ExceptionHandler(NotLoginException.class)
    public RE handleNotLoginException(NotLoginException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.warn("请求地址'{}',认证失败'{}',无法访问系统资源", requestURI, e.getMessage());
        return R.R(CodeEnum.authentication, "认证失败，无法访问系统资源");
    }

    /**
     * 无效认证
     */
    @ExceptionHandler(SameTokenInvalidException.class)
    public RE handleIdTokenInvalidException(SameTokenInvalidException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.warn("请求地址'{}',无效认证'{}',无法访问系统资源", requestURI, e.getMessage());
        return R.R(CodeEnum.authentication, "无效认证，无法访问系统资源");
    }

}
